'''
views.py - Django views, triggered by URL pattern matching in urls.py

Authors: Martin Norbury
         Eric Saunders

October 2011
'''

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
import json

from utils import set_type_from_string


@csrf_exempt
def dispatch(request, module_arg, arguments):
    ''' Given a module name, and a string of slash-delimited arguments, parse the
        request and pass it on to the appropriate server-side module for processing.
        Keyword arguments are extracted from the request as necessary. The return is
        a JSON dictionary.

        Both GET and POST are supported.
    '''

    module = __import__(module_arg)

    # If we've received a POST...
    if request.POST:
        # Deserialise the JSON payload from the request
        json_data = request.POST['data']
        data = json.loads(json_data)

        # Pass the arguments to the requested module
        args   = data['args']
        kwargs = data['kwargs']
        result_message = module.handle(*args,**kwargs)


    # ...otherwise, this is a GET request
    else:
        # By convention, args are specified as elements of the URL path
        args = arguments.split('/')

        # Parse the arguments and convert to numbers if appropriate
        args = [ set_type_from_string(a) for a in args if len(a) is not 0 ]

        # kwargs are passed as a URL query string (e.g. ?foo=bar&data=6)
        kwargs = request.GET

        # Pass the sanitised arguments to the requested module
        result_message = module.handle(*args,**kwargs)

    # Construct the return payload to send back to the client
    result = {
             'module'  : module_arg,
             'args'    : args,
             'kwargs'  : kwargs,
             'message' : result_message,
             }


    # JSON-encode the return, and send back the response
    return HttpResponse(json.dumps(result))
